import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/profile/introduction_setting/introduction_setting_page_logic.dart';
import 'package:edu/utils/account_info.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

/*
 * 更新签名
 */
class IntroductionSettingPage extends StatefulWidget {
  const IntroductionSettingPage({super.key});

  @override
  State<IntroductionSettingPage> createState() =>
      _IntroductionSettingPageState();
}

class _IntroductionSettingPageState extends State<IntroductionSettingPage> {
  @override
  void initState() {
    super.initState();
    context.read<IntroductionSettingPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<IntroductionSettingPageLogic>(
      builder: (context, logic, child) {
        return Scaffold(
          appBar: _buildAppBar(context, logic),
          body: _buildMainBody(context, logic),
        );
      },
    );
  }

  AppBar _buildAppBar(
    BuildContext context,
    IntroductionSettingPageLogic logic,
  ) {
    final fontSize =
        (Theme.of(context).appBarTheme.titleTextStyle?.fontSize ?? 20) - 2;

    return AppBar(
      title: const Text(AppStrings.editIntrodcution),
      actions: [
        TextButton(
          onPressed: logic.controller.text.isNotEmpty ? okAction : null,
          child: Text(AppStrings.ok, style: TextStyle(fontSize: fontSize)),
        ),
      ],
    );
  }

  Widget _buildMainBody(
    BuildContext context,
    IntroductionSettingPageLogic logic,
  ) {
    final longIntroduction =
        AccountInfo.shared.userBrief?.isTeacher ??
        AccountInfo.shared.userBrief?.isAdmin ??
        false;
    return Column(
      children: [
        const SizedBox(height: 15),
        TextField(
          decoration: const InputDecoration(
            // labelText: AppStrings.introduction,
            hintText: AppStrings.signatureHint,
            hintStyle: TextStyle(fontSize: 20),
            contentPadding: EdgeInsets.symmetric(horizontal: 15),
          ),
          controller: logic.controller,
          focusNode: logic.focusNode,
          maxLength: longIntroduction ? 1500 : 90,
          maxLines: longIntroduction ? 20 : 6,
        ),
      ],
    );
  }

  void okAction() async {
    final logic = context.read<IntroductionSettingPageLogic>();
    final introduction = logic.controller.text.trim();
    logic.focusNode.unfocus();
    logic.updateIntroduction(introduction).then((value) {
      if (mounted && value) {
        Navigator.of(context).pop();
      }
    });
  }
}
